#include <vector>
#include <queue>
#include "sched_rr.h"
#include "basesched.h"
#include <iostream>
#include <string>

using namespace std;
 

SchedRR::SchedRR(vector<int> argn) {
// Round robin recibe la cantidad de cores y sus cpu_quantum por parámetro
        quantum = argn.back();
        int i = argn[0];
        std::vector<int> temp (i);
        for (int j = 0 ; j < i ; j++){
        temp[j] = 0;
        }
        quantumporcpu = temp;


        //contQ = 0;
}

SchedRR::~SchedRR() {

}

void SchedRR::load(int pid) {	
	tareas.push(pid);
}

void SchedRR::unblock(int pid) {
	tareas.push(pid);
}

int SchedRR::tick(int cpu, const enum Motivo m) {
	int res;

		if (m == EXIT) {
        quantumporcpu[cpu] = 0;
		//	contQ = 0;

			
			if(tareas.empty()){
				res = IDLE_TASK;
			}
			else{
				res = tareas.front();
                tareas.pop();
			}
		}
		else if(m == BLOCK){
			quantumporcpu[cpu] = 0;
	
			if(tareas.empty()){
				res = IDLE_TASK;
			}
			else{
				res = tareas.front();
                tareas.pop();
			}
		}
		else if(m == TICK){
			quantumporcpu[cpu] = quantumporcpu[cpu] +1; 
			if(quantumporcpu[cpu] == quantum){
				quantumporcpu[cpu] = 0;
                if (tareas.empty()){
				res = current_pid(cpu);

                }
                else{
            	tareas.push(current_pid(cpu));
				res = tareas.front();
				tareas.pop();

                }
			}
			else{
				if(current_pid(cpu) == IDLE_TASK){
					if(tareas.empty()){
						quantumporcpu[cpu] = 0;
						res = current_pid(cpu);
					}
					else{
						quantumporcpu[cpu] = 0;
						res = tareas.front();
				        tareas.pop();
					}
				}
				else{
					res = current_pid(cpu);
				}
			}
		}
		else{
			// m == ERROR;
			cerr << "Error"<< endl;
			return -2;
		}

	return res;

}
